package com.ruoyi.web.controller.app;

import com.alibaba.fastjson.JSONArray;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;

import com.ruoyi.quartz.util.HttpUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.service.impl.AppNewsDetailedServiceImpl;
import com.ruoyi.system.service.impl.AppNewsTypesServiceImpl;
import com.ruoyi.web.controller.common.ConfigConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DecimalFormat;

import java.util.*;

@RestController
@RequestMapping("/app/common")
@Api("APP用户接口")
public class ForAppCommonController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private AppNewsDetailedServiceImpl appNewsDetailedService;
    @Resource
    private AppNewsTypesServiceImpl appNewsTypesService;
    @Autowired
    private ISysConfigAppService sysConfigService;
    @Autowired
    private IAppVersionsService iAppVersionsService;
    @Autowired
    private IAppDiscoversService iAppDiscoversService;
    @Autowired
    private IAppFunctionConfigurationService appFunctionConfigurationService;
    @Autowired
    private IBaseUserPrivilegesService iBaseUserPrivilegesService;
    @Autowired
    private IAppBannersService iAppBannersService;
    @Autowired
    private IAppCollectExpressionService iAppCollectExpressionService;
    final String IMG_FORMAT = "png_jpg_bmp_gif_tif_jpeg_pcx_PNG_JPG_BMP_GIF_TIF_JPEG_PCX";

    @Autowired
    private ISysConfigService configService;

    @ApiOperation("添加表情包")
    @RequestMapping(value = "addUserExpression", method = {RequestMethod.POST})
    public AjaxResult addUserExpression(Long userId,
                                        String expressionAddress,
                                        Integer height,
                                        Integer width,
                                        String type) throws IOException {
        String urlPath = expressionAddress;
        AppCollectExpression expression = new AppCollectExpression();
        expression.setCreateTime(new Date());
        expression.setUserId(userId);
        expression.setWidth(width);
        expression.setHeight(height);
        if (StringUtils.isNotEmpty(type) && type.equals("2")) {
            urlPath = downLoadByUrl(expressionAddress, UUID.randomUUID().toString().replace("-", ""));
            expression.setAddress(urlPath);
        } else {
            expression.setAddress(urlPath);
        }

        // 判断表情是否已存在
        AppCollectExpression expression_ex = new AppCollectExpression();
        expression_ex.setUserId(userId);
        expression_ex.setAddress(urlPath);
        List<AppCollectExpression> list = iAppCollectExpressionService.selectAppCollectExpressionList(expression_ex);
        if (list.size() > 0) {
            return AjaxResult.ok(-1, "已存在", "");
        }
        iAppCollectExpressionService.insertAppCollectExpression(expression);
        return AjaxResult.ok(0, "添加成功", "");
    }

    @ApiOperation("获取表情包集合")
    @RequestMapping(value = "getUserExpressionList", method = {RequestMethod.GET})
    public AjaxResult getUserExpressionList(Long userId) {
        AppCollectExpression expression = new AppCollectExpression();
        expression.setUserId(userId);
        return AjaxResult.ok(0, "", iAppCollectExpressionService.selectAppCollectExpressionList(expression));
    }

    @ApiOperation("删除表情包")
    @RequestMapping(value = "delExpressionById/{id}", method = {RequestMethod.DELETE})
    public AjaxResult delExpressionById(@PathVariable Long id) {
        iAppCollectExpressionService.deleteAppCollectExpressionById(id);
        return AjaxResult.ok(0, "", null);
    }

    @ApiOperation("获取发现页集合")
    @RequestMapping(value = "getDiscoversList", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult getDiscoversList() {
        QueryWrapper<AppDiscovers> ew = new QueryWrapper<>();
        ew.orderByDesc("sort");
        List<AppDiscovers> list = iAppDiscoversService.list(ew);
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        return AjaxResult.ok(0, "", map);
    }

    @ApiOperation("获取引导页")
    @RequestMapping(value = "getBanners", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult getBanners() {
        AppBanners banners = new AppBanners();
        banners.setType(1);
        List<AppBanners> list = iAppBannersService.selectAppBannersList(banners);
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        return AjaxResult.ok(0, "", map);
    }

    @ApiOperation("获取启动页")
    @RequestMapping(value = "getStartupPics", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult getStartupPics() {
        AppBanners banners = new AppBanners();
        banners.setType(2);
        List<AppBanners> list = iAppBannersService.selectAppBannersList(banners);
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        return AjaxResult.ok(0, "", map);
    }


    @ApiOperation("获取配置项-是否启动邀请码")
    @RequestMapping(value = "getAppConfigForInvitation", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult getAppConfigForInvitation() {
        AppFunctionConfiguration info = appFunctionConfigurationService.selectAppFunctionConfigurationById(10001L);
        Map<String, Object> map = new HashMap<>();
        map.put("invitationCodeState", info.getInvitationCodeState());

        return AjaxResult.ok(0, "", map);
    }

    @ApiOperation("获取配置项")
    @RequestMapping(value = "getAppConfig", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult getAppConfig() {
        AppFunctionConfiguration info = appFunctionConfigurationService.selectAppFunctionConfigurationById(10001L);
        QueryWrapper<BaseUserPrivileges> ew = new QueryWrapper<>();
        ew.eq("account", getUserId());
        BaseUserPrivileges privileges = iBaseUserPrivilegesService.getOne(ew);
        if (privileges != null) {
            info.setAddFriendState(1L);
            info.setAddGroupState(1L);
            info.setDynamicState(1L);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("list", info);

        return AjaxResult.ok(0, "", map);
    }

    @ApiOperation("获App取版本号")
    @RequestMapping(value = "getAppVersions", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult getAppVersions() {
        AppVersions appVersions = new AppVersions();
        List<AppVersions> list = iAppVersionsService.selectAppVersionsList(appVersions);
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        if (list.size() > 0) {
            return AjaxResult.ok(0, "", map);
        }
        return AjaxResult.ok(-1, "", null);
    }

    @ApiOperation("获取发现网址")
    @RequestMapping(value = "getFoundUrl", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult getFoundUrl() {
        String value = sysConfigService.getValue(ConfigConstant.FOUND_URL);
        Map<String, Object> map = new HashMap<>();
        map.put("foundUrl", value);
        return AjaxResult.ok(0, "", map);
    }

    @ApiOperation("获取协议内容")
    @RequestMapping(value = "getAgreement", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult getAgreement(@ApiParam("类型，0：隐私，1：服务") @RequestParam Integer type) {
        String value = sysConfigService.getValue(type == 0 ? ConfigConstant.PRIVACY_AGREEMENT : ConfigConstant.SERVER_AGREEMENT);
        Map<String, Object> map = new HashMap<>();
        map.put("agreement", value);
        return AjaxResult.ok(0, "", map);
    }

    /**
     * 上传图片
     */
    @PostMapping("/upload")
    @ApiOperation("上传图片")
    public AjaxResult upload(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 务必，防止返回文件名是乱码
            response.setCharacterEncoding("utf-8");
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multipartRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multipartRequest.getFile(iter.next());
                if (file.isEmpty()) {
                    return AjaxResult.error(-1, "文件不能为空");
                }
                Long fileSize = file.getSize();
                if (fileSize > 10485760) {
                    return AjaxResult.error(-1, "上传失败：文件大小不能超过10M");
                }
                //获取文件后缀
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                if (IMG_FORMAT.indexOf(suffix) == -1) {
                    return AjaxResult.error(-1, "上传失败：文件格式不正确");
                }

                String path = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
                Map<String, Object> map = new HashMap<>();
                map.put("data", path);
                return AjaxResult.ok(0, "上传成功", map);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(-1, "上传失败：上传文件出现错误");
        }
        return AjaxResult.error(-1, "上传失败：上传文件出现错误");
    }

    public static String downLoadByUrl(String urlStr, String fileName) throws IOException {
        String suffix = ".png";
        if (urlStr.indexOf(".gif") > -1) {
            suffix = ".gif";
        }
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(5 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream2(inputStream);

        //获取项目根目录地址
        String propertiesFile = RuoYiConfig.getProfile();
        //文件保存位置
        File saveDir = new File(propertiesFile);
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        File file = new File(saveDir + File.separator + fileName + suffix);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if (fos != null) {
            fos.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }
        return "/profile/" + fileName + suffix;
    }

    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream2(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    /**
     * 读取body
     *
     * @param request
     * @return
     * @throws IOException
     */
    private byte[] readBody(HttpServletRequest request) throws IOException {
        if (request.getContentLength() > 0) {
            byte[] body = new byte[request.getContentLength()];
            IOUtils.readFully(request.getInputStream(), body);
            return body;
        } else {
            return null;
        }
    }


    /**
     * 查询新闻列表
     */
    @RequestMapping(value = "getNewList", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation("获取新闻列表")
    public AjaxResult getNewList(AppNewsDetailed appNewsDetailed) {
        startPage();
        if (appNewsDetailed.getNewsTypeName() != null) {
            if (appNewsDetailed.getNewsTypeName().equals("全部")) {
                appNewsDetailed.setNewsTypeName("");
            }
        }
        List<AppNewsDetailed> list = appNewsDetailedService.selectAppNewsDetailedList(appNewsDetailed);
        return AjaxResult.ok(0, "", getDataTable(list));
    }

    /**
     * 根据新闻id查询新闻详情
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "getNewListById", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation("获取新闻信息")
    public AjaxResult getCollectInfo(@ApiParam("新闻id") @RequestParam Long id) {
        Map<String, Object> map = new HashMap<>();
        map.put("newDetailed", appNewsDetailedService.getById(id));
        return AjaxResult.ok(0, "", map);
    }

    /**
     * 获取新闻类型
     *
     * @return
     */
    @RequestMapping(value = "getNewTypeList", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation("获取新闻类型")
    public AjaxResult getNewTypeList() {

        Map<String, Object> map = new HashMap<>();
        map.put("newTypes", appNewsTypesService.findList(new AppNewsTypes()));
        return AjaxResult.ok(0, "", map);
    }

    /**
     * 大盘指数每日指标
     * index_dailybasic
     * trade_date	str	N	交易日期 （格式：YYYYMMDD，比如20181018，下同）
     * ts_code	str	N	TS代码
     *
     * @return list
     */
    @RequestMapping(value = "getIndexDailybasic", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation("大盘指数每日指标")
    public AjaxResult getIndexDailybasic() {
        //参数 parm
        Map<String, Object> parm = new HashMap<>();
        parm.put("api_name", "index_dailybasic");
        parm.put("token", "02c63af7892cf38474327f022280ebdbe8d330f3abef5f86994a41be");
        Date times = new Date();
        String nuclease = null;
        JSONArray jsonArray = null;
        int i = 0;
        try {
            do {
                Map<String, String> mapParm = new HashMap<>();
                mapParm.put("list_status", "L");
                mapParm.put("trade_date", DateUtils.parseDateToStr("yyyyMMdd", DateUtils.addDays(times, -i)));
                mapParm.put("ts_code", "");
                parm.put("params", mapParm);
                parm.put("fields", "ts_code,trade_date,total_mv,float_mv,total_share,float_share,free_share,turnover_rate,pe,pe_ttm,pb");
                nuclease = HttpUtils.postBody("http://api.tushare.pro", JSONObject.toJSONString(parm));
                //插接返回参数
                JSONObject resObject = JSONObject.parseObject(nuclease);
                String data = resObject.getString("data");
                JSONObject items = JSONObject.parseObject(data);
                jsonArray = items.getJSONArray("items");
                i++;
            } while (jsonArray.size() == 0);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.ok(0, "", jsonArray);
    }


    @RequestMapping(value = "getIndexDailybasic2", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation("大盘指数每日指标")
    public AjaxResult getIndexDailybasic2() throws IOException {
        //参数 parm
        Map<String, Object> parm = new HashMap<>();
        parm.put("api_name", "index_daily");
        parm.put("token", "02c63af7892cf38474327f022280ebdbe8d330f3abef5f86994a41be");
        Date times = new Date();
        List<Map<String, Object>> list = Lists.newArrayList();
        String nuclease = null;
        JSONArray jsonArray = null;
        Map<String, String> mapParm = new HashMap<>();
        mapParm.put("list_status", "L");
        mapParm.put("ts_code", "000001.SH");
        parm.put("params", mapParm);
        parm.put("fields", "ts_code,change,pct_chg,close");
        nuclease = HttpUtils.postBody("http://api.tushare.pro", JSONObject.toJSONString(parm));
        System.out.println("nuclease1:" + nuclease);
        //插接返回参数
        JSONObject resObject = JSONObject.parseObject(nuclease);
        String data = resObject.getString("data");
        JSONObject items = JSONObject.parseObject(data);
        jsonArray = items.getJSONArray("items");

        Map<String, Object> map = new HashMap<>();
        map.put("tsName", "上证指数");
        map.put("ts_code", jsonArray.getJSONArray(0).get(0));
        map.put("close", jsonArray.getJSONArray(0).get(1));
        map.put("change", jsonArray.getJSONArray(0).get(2));
        Double pct_chg = jsonArray.getJSONArray(0).getDouble(3) * 100;
        DecimalFormat format = new DecimalFormat("#.00");
        map.put("pct_chg", format.format(pct_chg) + "%");

        list.add(map);

        // ++++++++++++
        String nuclease2 = null;
        JSONArray jsonArray2 = null;
        Map<String, String> mapParm2 = new HashMap<>();
        mapParm2.put("list_status", "L");
        mapParm2.put("ts_code", "399001.SZ");
        parm.put("params", mapParm2);
        parm.put("fields", "ts_code,change,pct_chg,close");
        nuclease2 = HttpUtils.postBody("http://api.tushare.pro", JSONObject.toJSONString(parm));
        //插接返回参数
        JSONObject resObject2 = JSONObject.parseObject(nuclease2);
        String data2 = resObject2.getString("data");
        JSONObject items2 = JSONObject.parseObject(data2);
        jsonArray2 = items2.getJSONArray("items");

        Map<String, Object> map2 = new HashMap<>();
        map2.put("tsName", "深证成指");
        map2.put("ts_code", jsonArray2.getJSONArray(0).get(0));
        map2.put("close", jsonArray2.getJSONArray(0).get(1));
        map2.put("change", jsonArray2.getJSONArray(0).get(2));
        Double pct_chg2 = jsonArray2.getJSONArray(0).getDouble(3) * 100;
        map2.put("pct_chg", format.format(pct_chg2) + "%");

        list.add(map2);

        //+++++++++++
        String nuclease3 = null;
        JSONArray jsonArray3 = null;
        Map<String, String> mapParm3 = new HashMap<>();
        mapParm3.put("list_status", "L");
        mapParm3.put("ts_code", "399006.SZ");
        parm.put("params", mapParm3);
        parm.put("fields", "ts_code,change,pct_chg,close");
        nuclease3 = HttpUtils.postBody("http://api.tushare.pro", JSONObject.toJSONString(parm));
        //插接返回参数
        JSONObject resObject3 = JSONObject.parseObject(nuclease3);
        String data3 = resObject3.getString("data");
        JSONObject items3 = JSONObject.parseObject(data3);
        jsonArray3 = items3.getJSONArray("items");

        Map<String, Object> map3 = new HashMap<>();
        map3.put("tsName", "创业板指");
        map3.put("ts_code", jsonArray3.getJSONArray(0).get(0));
        map3.put("close", jsonArray3.getJSONArray(0).get(1));
        map3.put("change", jsonArray3.getJSONArray(0).get(2));
        Double pct_chg3 = jsonArray3.getJSONArray(0).getDouble(3) * 100;
        map3.put("pct_chg", format.format(pct_chg3) + "%");
        list.add(map3);

        return AjaxResult.ok(0, "", list);
    }

    @RequestMapping(value = "getCollectionAddress", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation("获取平台收款地址")
    public AjaxResult getCollectionAddress() {
        String blackStr = configService.selectConfigByKey("collection.address");
        return AjaxResult.ok(0, "", blackStr);
    }

}
